<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import { Search, Message, Grid, Plus, Setting, User, Upload, Edit, Delete, Top, MoreFilled, Download } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import ToggleTheme from "@/components/ToggleTheme.vue"
import AvatarSelection from "@/components/AvatarSelection.vue"
import { getUserConversations, getUserInfo, renameConversation, deleteConversation, toggleConversationTop } from '@/api/user.js'
import { exportConversationToPdf, exportConversationToMarkdown, downloadFile } from '@/api/chat.js'
import { update } from '@/api/auth.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useThemeStore } from "@/stores/theme"
import noAvatar from "@/assets/images/no-avatar.png"

// 主题切换
const themeStore = useThemeStore()

const router = useRouter()

// 用户信息
const userInfo = ref({
  username: '加载中...',
  avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
})

// 历史会话列表
const conversationList = ref([])

// 搜索关键词
const searchQuery = ref('')
const loading = ref(false)
const showUserMenu = ref(false)

// 头像选择相关
const avatarSelectionVisible = ref(false)

// 个人中心弹窗相关
const userCenterDialogVisible = ref(false)
const userFormRef = ref()
const userFormLoading = ref(false)

// 重命名对话弹窗相关
const renameDialogVisible = ref(false)
const renameForm = reactive({
  memoryId: '',
  title: ''
})

// 用户表单数据
const userForm = reactive({
  id: null,
  nickname: '',
  username: '',
  sex: '男',
  age: 18,
  phone: '',
  email: '',
  avatar: '',
  password: '',
  confirmPassword: ''
})

// 原始用户数据，用于重置
const originalUserData = reactive({})

// 表单验证规则
const formRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 150, message: '年龄必须在 1 到 150 之间', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (userForm.password && value !== userForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200 && res.data) {
      userInfo.value = res.data
    } else {
      // 如果API调用失败，尝试从localStorage获取
      const storedUserInfo = localStorage.getItem('userInfo')
      if (storedUserInfo) {
        userInfo.value = JSON.parse(storedUserInfo)
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 尝试从localStorage获取
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      userInfo.value = JSON.parse(storedUserInfo)
    }
  }
}

// 会话列表是否已加载完成
const isConversationsLoaded = ref(false)

// 获取会话列表
const fetchConversations = async () => {
  loading.value = true

  try {
    const res = await getUserConversations()
    if (res && res.code === 200 && res.data) {
      conversationList.value = res.data
      isConversationsLoaded.value = true
    } else {
      console.warn('获取会话列表返回数据异常:', res)
      ElMessage.warning('获取会话列表失败')
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
    // 如果是token相关错误，不显示额外的错误消息，因为request.js已经处理了
    if (!error.message || !error.message.includes('token无效')) {
      ElMessage.error('获取会话列表失败')
    }
  } finally {
    loading.value = false
  }
}

// 搜索对话
const searchConversations = () => {
  if (!searchQuery.value.trim()) {
    fetchConversations()
    return
  }

  // 本地搜索实现
  const query = searchQuery.value.toLowerCase()
  const filteredList = conversationList.value.filter(
    item => item.title.toLowerCase().includes(query)
  )
  conversationList.value = filteredList
}

// 创建新对话
const createNewChat = () => {
  // 发送创建新对话事件
  emit('create-new-chat')
  // 如果在聊天页面，保持在当前页面；如果在其他页面，跳转到聊天页面
  if (!router.currentRoute.value.path || !router.currentRoute.value.path.includes('/chat')) {
    router.push('/')
  }
}

// 在script setup中添加事件定义
// 定义事件
const emit = defineEmits(['select-character', 'select-conversation', 'create-new-chat', 'show-role-square', 'show-role-manage', 'conversation-deleted'])

// 修改跳转到角色广场的函数
const goToRoleSquare = () => {
  emit('show-role-square')
}

// 新增跳转到个人角色管理的函数
const goToRoleManage = () => {
  emit('show-role-manage')
}

// 打开对话
const openConversation = (conversation) => {
  emit('select-conversation', conversation)
  router.push(`/chat/${conversation.id}`)
}

// 阻止事件冒泡
const stopPropagation = (event) => {
  event.stopPropagation()
}

// 重命名对话
const openRenameDialog = (conversation, event) => {
  stopPropagation(event)
  renameForm.memoryId = conversation.id
  renameForm.title = conversation.title
  renameDialogVisible.value = true
}

// 确认重命名
const confirmRename = async () => {
  if (!renameForm.title.trim()) {
    ElMessage.warning('请输入新的标题')
    return
  }

  try {
    const res = await renameConversation(renameForm.memoryId, renameForm.title.trim())
    if (res.code === 200) {
      ElMessage.success('重命名成功')
      renameDialogVisible.value = false
      fetchConversations() // 重新获取会话列表
    } else {
      ElMessage.error(res.msg || '重命名失败')
    }
  } catch (error) {
    console.error('重命名失败:', error)
    ElMessage.error('重命名失败，请稍后重试')
  }
}

// 删除对话
const deleteConversationHandler = async (conversation, event) => {
  stopPropagation(event)
  
  try {
    await ElMessageBox.confirm(
      `确定要删除对话 "${conversation.title}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const res = await deleteConversation(conversation.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 发送删除事件，通知父组件
      emit('conversation-deleted', conversation.id)
      fetchConversations() // 重新获取会话列表
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除对话失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 置顶/取消置顶对话
const toggleConversationTopHandler = async (conversation, event) => {
  stopPropagation(event)
  
  try {
    const newTopStatus = conversation.isTop === "1" ? "0" : "1"
    const statusText = newTopStatus === "1" ? '置顶' : '取消置顶'

    const res = await toggleConversationTop(conversation.id, newTopStatus)
    if (res.code === 200) {
      ElMessage.success(`${statusText}成功`)
      fetchConversations() // 重新获取会话列表
    } else {
      ElMessage.error(res.msg || `${statusText}失败`)
    }
  } catch (error) {
    console.error('置顶操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 导出对话
const exportConversationHandler = async (conversation, format, event) => {
  stopPropagation(event)
  
  try {
    let response
    let filename
    const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-')
    
    if (format === 'pdf') {
      response = await exportConversationToPdf(conversation.id)
      filename = `conversation_${conversation.title}_${timestamp}.pdf`
    } else if (format === 'markdown') {
      response = await exportConversationToMarkdown(conversation.id)
      filename = `conversation_${conversation.title}_${timestamp}.md`
    }

    if (response) {
      downloadFile(response, filename)
      ElMessage.success(`导出${format.toUpperCase()}成功`)
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error(`导出${format.toUpperCase()}失败，请稍后重试`)
  }
}

// 打开个人中心弹窗
const goToUserCenter = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200 && res.data) {
      const userData = res.data
      Object.assign(userForm, {
        id: userData.id,
        nickname: userData.nickname,
        username: userData.username,
        sex: userData.sex,
        age: userData.age,
        phone: userData.phone,
        email: userData.email,
        avatar: userData.avatar,
        password: '',
        confirmPassword: ''
      })

      // 保存原始数据用于重置
      Object.assign(originalUserData, userData)
      
      userCenterDialogVisible.value = true
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 更新用户信息
const updateUserInfo = async () => {
  try {
    await userFormRef.value.validate()

    userFormLoading.value = true

    // 准备更新数据
    const updateData = {
      id: userForm.id,
      nickname: userForm.nickname,
      sex: userForm.sex,
      age: userForm.age,
      phone: userForm.phone,
      email: userForm.email,
      avatar: userForm.avatar,
      username: userForm.username
    }

    // 检查是否修改了密码
    const isPasswordChanged = userForm.password && userForm.password.trim() !== ''

    // 如果修改了密码，则包含密码字段
    if (isPasswordChanged) {
      updateData.password = userForm.password
    }

    const res = await update(updateData)

    if (res.code === 200) {
      ElMessage.success('更新成功')

      // 如果修改了密码，自动退出登录
      if (isPasswordChanged) {
        ElMessage.success('密码修改成功，请重新登录')

        // 清除本地存储
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')

        // 关闭弹窗
        userCenterDialogVisible.value = false

        // 延迟1秒后跳转到登录页
        setTimeout(() => {
          router.push('/login')
        }, 1000)

        return // 直接返回，不执行后续代码
      }

      // 更新本地存储的用户信息（非密码修改情况）
      const updatedUserInfo = { ...originalUserData, ...updateData }
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))

      // 更新当前显示的用户信息
      userInfo.value = updatedUserInfo

      // 清空密码字段
      userForm.password = ''
      userForm.confirmPassword = ''

      // 更新原始数据
      Object.assign(originalUserData, updatedUserInfo)

      // 关闭弹窗
      userCenterDialogVisible.value = false
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新失败')
  } finally {
    userFormLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  ElMessageBox.confirm('确定要重置所有修改吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    Object.assign(userForm, {
      ...originalUserData,
      password: '',
      confirmPassword: ''
    })
    userFormRef.value.clearValidate()
    ElMessage.success('已重置')
  }).catch(() => {})
}

// 退出登录
const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  router.push('/login')
  ElMessage.success('已退出登录')
}

// 显示头像选择对话框
const showAvatarSelection = () => {
  avatarSelectionVisible.value = true
}

// 处理头像选择结果
const handleAvatarSelected = (avatarUrl) => {
  userInfo.value.avatar = avatarUrl
  userForm.avatar = avatarUrl
  ElMessage.success('头像更新成功')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUserInfo()
  fetchConversations()
})

// 暴露方法给父组件
defineExpose({
  fetchConversations,
  conversationList,
  isConversationsLoaded
})
</script>

<template>
  <div class="sidebar" :class="{ 'dark-mode': themeStore.isDark }">
    <!-- 第一块：系统标题和主题切换 -->
    <div class="sidebar-header">
      <div class="logo-area">
        <img src="/src/assets/logo.png" alt="Logo" class="logo" />
        <span class="logo-text">AI角色扮演</span>
      </div>
      <ToggleTheme class="theme-toggle" />
    </div>

    <!-- 第二块：功能按钮区域 -->
    <div class="sidebar-actions">
      <div class="glass-buttons-container">
        <el-button type="primary" class="glass-button new-chat-btn" @click="createNewChat">
          <el-icon><Plus /></el-icon>创建新对话
        </el-button>
        <el-button type="success" class="glass-button role-square-btn" @click="goToRoleSquare">
          <el-icon><Grid /></el-icon>角色广场
        </el-button>
      </div>
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索对话..."
          class="search-input"
          clearable
          @input="searchConversations"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 第三块：对话列表 -->
    <div class="history-list">
      <div class="history-title">历史对话</div>
      <el-empty v-if="conversationList.length === 0 && !loading" description="暂无对话记录" />
      <el-skeleton v-if="loading" :rows="5" animated />
      <div
        v-else
        v-for="(conversation, index) in conversationList"
        :key="conversation.id"
        class="history-item"
        :class="{ 'is-top': conversation.isTop === '1' }"
        @click="openConversation(conversation)"
      >
        <el-icon><Message /></el-icon>
        <div class="conversation-info">
          <div class="conversation-title-wrapper">
            <span class="conversation-title">{{ conversation.title }}</span>
            <el-icon v-if="conversation.isTop === '1'" class="top-icon">
              <Top />
            </el-icon>
          </div>
          <div class="conversation-meta">
            <el-tag size="small" type="info" class="role-tag" v-if="conversation.roleName">
              {{ conversation.roleName }}
            </el-tag>
            <span class="conversation-time" v-if="conversation.time">
              {{ conversation.time }}
            </span>
          </div>
        </div>
        <!-- 会话操作按钮 -->
        <div class="conversation-actions" @click="stopPropagation">
          <el-dropdown trigger="click" placement="bottom-end" @click="stopPropagation">
            <el-button size="small" type="default" :icon="MoreFilled" circle class="action-btn" />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="openRenameDialog(conversation, $event)">
                  <el-icon><Edit /></el-icon>
                  重命名
                </el-dropdown-item>
                <el-dropdown-item @click="toggleConversationTopHandler(conversation, $event)">
                  <el-icon><Top /></el-icon>
                  {{ conversation.isTop === "1" ? '取消置顶' : '置顶' }}
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-dropdown trigger="hover" placement="left-start">
                    <span>
                      <el-icon><Download /></el-icon>
                      导出
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="exportConversationHandler(conversation, 'pdf', $event)">
                          导出为PDF
                        </el-dropdown-item>
                        <el-dropdown-item @click="exportConversationHandler(conversation, 'markdown', $event)">
                          导出为Markdown
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-dropdown-item>
                <el-dropdown-item @click="deleteConversationHandler(conversation, $event)" divided>
                  <el-icon><Delete /></el-icon>
                  <span style="color: var(--el-color-danger)">删除</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 第四块：用户信息 -->
    <div class="user-info">
      <div class="user-avatar-name">
        <el-avatar
          :size="36"
          :src="userInfo.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"
          class="clickable-avatar"
        />
        <span class="username">{{ userInfo.nickname }}</span>
      </div>

      <div class="user-actions">
        <el-dropdown trigger="click" @command="command => {
          if (command === 'userCenter') {
            goToUserCenter()
          } else if (command === 'roleManage') {
            goToRoleManage()
          } else {
            logout()
          }
        }">
          <el-button type="info" text>
            <el-icon><Setting /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="userCenter">
                <el-icon><User /></el-icon>个人中心
              </el-dropdown-item>
              <el-dropdown-item command="roleManage">
                <el-icon><Grid /></el-icon>个人角色管理
              </el-dropdown-item>
              <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 重命名对话弹窗 -->
    <el-dialog
      v-model="renameDialogVisible"
      title="重命名对话"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form label-width="80px">
        <el-form-item label="新标题">
          <el-input
            v-model="renameForm.title"
            placeholder="请输入新的对话标题"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRename">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 个人中心弹窗 -->
    <el-dialog
      v-model="userCenterDialogVisible"
      title="个人信息"
      width="600px"
      :close-on-click-modal="false"
      class="user-center-dialog"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="formRules"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="头像" prop="avatar">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="点击更换头像"
            placement="top"
          >
            <el-avatar
              :src="userForm.avatar || noAvatar"
              @click="showAvatarSelection"
              style="cursor: pointer;"
              class="user-avatar"
              :size="60"
            />
            <el-input v-model="userForm.avatar" type="hidden"></el-input>
          </el-tooltip>
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="用户名">
          <el-input v-model="userForm.username" disabled />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio value="男">男</el-radio>
            <el-radio value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="userForm.age" :min="1" :max="150" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="不修改请留空"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="userForm.confirmPassword"
            type="password"
            placeholder="不修改请留空"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="userCenterDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateUserInfo" :loading="userFormLoading">
            保存修改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 头像选择弹窗 -->
    <AvatarSelection
      v-model="avatarSelectionVisible"
      :current-avatar="userForm.avatar"
      @avatar-selected="handleAvatarSelected"
    />
  </div>
</template>

<style scoped>
.sidebar {
  width: 280px;
  background-color: var(--el-bg-color-page, #f5f7fa);
  border-right: 1px solid var(--el-border-color-light, #e6e6e6);
  display: flex;
  flex-direction: column;
  height: 100%;
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.sidebar.dark-mode {
  background-color: var(--el-bg-color-overlay, #1f2937);
  border-right-color: var(--el-border-color-darker, #374151);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
}

.sidebar-header {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid var(--el-border-color-light, #e6e6e6);
}

.logo-area {
  display: flex;
  align-items: center;
}

.logo {
  width: 28px;
  height: 28px;
  margin-right: 10px;
}

.logo-text {
  font-weight: bold;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.sidebar-actions {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 按钮容器样式 */
.glass-buttons-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 8px;
  align-items: stretch; /* 确保按钮宽度一致 */
}

/* 按钮基础样式优化 */
.new-chat-btn, .role-square-btn {
  width: 100% !important;
  height: 48px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  gap: 8px;
  border-radius: 12px !important;
  font-weight: 500;
  padding: 0 20px !important;
  margin: 0 !important;
  transition: all 0.3s ease;
  border: none !important;
  position: relative;
  overflow: hidden;
  font-size: 14px !important;
  letter-spacing: 0.5px;
  text-align: center;
  white-space: nowrap;
  box-sizing: border-box !important;
}

/* 重置Element Plus按钮默认样式 */
.new-chat-btn.el-button,
.role-square-btn.el-button {
  min-height: 48px !important;
  line-height: 1 !important;
  vertical-align: top !important;
}

/* 确保图标对齐 */
.new-chat-btn .el-icon,
.role-square-btn .el-icon {
  font-size: 16px !important;
  margin-right: 0 !important;
  margin-left: 0 !important;
  vertical-align: middle !important;
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  transition: transform 0.3s ease;
}

/* 创建新对话按钮特殊样式 */
.new-chat-btn {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(64, 158, 255, 0.3);
}

.new-chat-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.4);
  background: linear-gradient(135deg, #337ecc 0%, #529b2e 100%);
}

.new-chat-btn:active {
  transform: translateY(-1px);
}

/* 角色广场按钮特殊样式 */
.role-square-btn {
  background: linear-gradient(135deg, #67c23a 0%, #e6a23c 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(103, 194, 58, 0.3);
}

.role-square-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(103, 194, 58, 0.4);
  background: linear-gradient(135deg, #529b2e 0%, #b88230 100%);
}

.role-square-btn:active {
  transform: translateY(-1px);
}

.new-chat-btn:hover .el-icon,
.role-square-btn:hover .el-icon {
  transform: scale(1.1);
}

/* 暗色模式下的按钮样式 */
.sidebar.dark-mode .new-chat-btn {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  box-shadow: 0 4px 15px rgba(64, 158, 255, 0.2);
}

.sidebar.dark-mode .role-square-btn {
  background: linear-gradient(135deg, #67c23a 0%, #e6a23c 100%);
  box-shadow: 0 4px 15px rgba(103, 194, 58, 0.2);
}

.sidebar.dark-mode .new-chat-btn:hover {
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.3);
}

.sidebar.dark-mode .role-square-btn:hover {
  box-shadow: 0 8px 25px rgba(103, 194, 58, 0.3);
}

.search-container {
  margin-top: 4px;
}

.search-input {
  width: 100%;
  border-radius: 8px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 8px;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px;
  margin-top: 8px;
}

.history-title {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 12px;
  padding-left: 4px;
  font-weight: 500;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 6px;
  transition: all 0.3s;
  color: var(--el-text-color-primary);
  position: relative;
}

.history-item:hover {
  background-color: var(--el-color-primary-light-9);
  transform: translateX(2px);
}

.history-item.is-top {
  background-color: var(--el-color-warning-light-9);
  border-left: 3px solid var(--el-color-warning);
}

.history-item.is-top:hover {
  background-color: var(--el-color-warning-light-8);
}

.history-item:hover .conversation-actions {
  opacity: 1;
}

.history-item .el-icon {
  margin-right: 10px;
  font-size: 18px;
  color: var(--el-color-primary);
  flex-shrink: 0;
}

.conversation-info {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
  margin-right: 8px;
}

.conversation-title-wrapper {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 4px;
}

.conversation-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.top-icon {
  color: var(--el-color-warning);
  font-size: 14px;
  flex-shrink: 0;
}

.conversation-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
  margin-top: 4px;
}

.role-tag {
  font-size: 10px;
  padding: 0 6px;
  height: 18px;
  line-height: 16px;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex-shrink: 0;
}

.conversation-time {
  font-size: 11px;
  color: var(--el-text-color-placeholder);
  white-space: nowrap;
  flex-shrink: 0;
  margin-top: 2px;
}

.dark-mode .conversation-time {
  color: var(--el-text-color-disabled);
}

.conversation-actions {
  opacity: 0;
  transition: opacity 0.3s;
  flex-shrink: 0;
}

.action-btn {
  width: 24px;
  height: 24px;
  padding: 0;
  border: none;
  background: transparent;
  color: var(--el-text-color-secondary);
}

.action-btn:hover {
  background-color: var(--el-color-primary-light-8);
  color: var(--el-color-primary);
}

.user-info {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-top: 1px solid var(--el-border-color-light, #e6e6e6);
  margin-top: auto;
}

.user-avatar-name {
  display: flex;
  align-items: center;
}

.clickable-avatar {
  cursor: pointer;
  transition: transform 0.3s;
}

.clickable-avatar:hover {
  transform: scale(1.1);
}

.username {
  margin-left: 12px;
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.user-actions {
  display: flex;
  align-items: center;
}

.user-actions .el-button {
  font-size: 18px;
}

/* 头像选择相关样式 */
.avatar-selection {
  max-height: 70vh;
  overflow-y: auto;
}

.upload-preview-section {
  min-height: 200px;
  margin-bottom: 24px;
}

.upload-preview-container {
  display: flex;
  gap: 24px;
}

.upload-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px;
}

.upload-icon {
  margin-bottom: 8px;
}

.upload-text {
  font-size: 16px;
  color: var(--el-text-color-primary);
  margin: 0;
}

.upload-hint {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin: 0;
}

.preview-section {
  flex: 1;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.preview-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex: 1;
  align-items: center;
  justify-content: center;
}

.preview-item {
  text-align: center;
}

.preview-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 16px;
  color: var(--el-text-color-primary);
}

.preset-avatars-section {
  border-top: 1px solid var(--el-border-color-light);
  padding-top: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 16px;
  color: var(--el-text-color-primary);
}

.preset-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.preset-avatar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 12px;
  border-radius: 8px;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.preset-avatar-item:hover {
  background-color: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary-light-7);
}

.preset-avatar-item.selected {
  background-color: var(--el-color-primary-light-8);
  border-color: var(--el-color-primary);
}

.preset-avatar {
  margin-bottom: 8px;
}

.preset-avatar-name {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  text-align: center;
}

/* 用户中心弹窗样式 */
.user-center-dialog {
  border-radius: 12px;
}

.user-center-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
  color: white;
  padding: 20px 24px;
  border-radius: 12px 12px 0 0;
}

.user-center-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

.user-center-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

.user-center-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.user-form {
  max-height: 60vh;
  overflow-y: auto;
}

.user-avatar {
  border: 3px solid var(--el-color-primary-light-8);
  transition: all 0.3s;
}

.user-avatar:hover {
  border-color: var(--el-color-primary);
  transform: scale(1.05);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 100%;
  }
  
  .preset-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 480px) {
  .preset-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .user-center-dialog {
    width: 95% !important;
  }
}
</style>
